package com.nowcoder.code.hjnc;

import com.algorithm.model.ListNode;
import com.algorithm.model.ListNodeService;

import java.util.Stack;

public class NC40 {

    public ListNode addInList(ListNode head1, ListNode head2) {

        Stack<ListNode> stack1 = new Stack<>();
        while (head1 != null) {
            stack1.push(head1);
            head1 = head1.next;
        }
        Stack<ListNode> stack2 = new Stack<>();
        while (head2 != null) {
            stack2.push(head2);
            head2 = head2.next;
        }
        if (stack1.size() < stack2.size()) {
            Stack<ListNode> tmp = stack1;
            stack1 = stack2;
            stack2 = tmp;
        }

        int j = 0;
        ListNode node = null;
        while (stack1.size() > 0) {
            node = stack1.pop();
            int sum = stack2.size() == 0 ? node.val + j : stack2.pop().val + node.val + j;
            j = sum / 10;
            sum = sum % 10;
            node.val = sum;
        }

        if (node != null && j != 0) {
            ListNode node1 = new ListNode(j);
            node1.next = node;
            node = node1;
        }

        return node;
    }

    public static void main(String[] args) {
        int[] i1 = {9, 3, 7};
        int[] i2 = {6, 3};
        ListNode listNode1 = ListNodeService.getByArray(i1);
        ListNode listNode2 = ListNodeService.getByArray(i2);

        ListNodeService.print(new NC40().addInList(listNode1, listNode2));

    }

}
